"""
JSON抽象层 - 统一JSON处理，支持可替换的JSON库
遵循Linus原则：消除特殊情况，一个接口解决所有问题
"""

import json as _json
from typing import Any, Dict, Optional, TYPE_CHECKING, cast
from abc import ABC, abstractmethod

if TYPE_CHECKING:
    import orjson


class JSONProvider(ABC):
    """JSON提供者抽象基类 - 统一接口"""
    
    @abstractmethod
    def dumps(self, obj: Any) -> str:
        """序列化对象为JSON字符串"""
        pass
    
    @abstractmethod
    def loads(self, s: str) -> Any:
        """从JSON字符串反序列化"""
        pass
    
    @property
    @abstractmethod
    def name(self) -> str:
        """提供者名称"""
        pass


class StandardJSON(JSONProvider):
    """标准JSON库提供者"""
    
    def dumps(self, obj: Any) -> str:
        return _json.dumps(obj, ensure_ascii=False, separators=(',', ':'))
    
    def loads(self, s: str) -> Any:
        return _json.loads(s)
    
    @property
    def name(self) -> str:
        return "standard"


class OrjsonJSON(JSONProvider):
    """orjson提供者 - 高性能JSON库"""
    
    def __init__(self):
        self._orjson_module: Optional[Any] = None
        self._import_error: Optional[str] = None
        self._try_import()
    
    def _try_import(self) -> None:
        """尝试导入orjson模块"""
        try:
            import orjson  # type: ignore
            self._orjson_module = orjson
        except ImportError as e:
            self._import_error = str(e)
    
    def _check_available(self) -> None:
        """检查orjson是否可用"""
        if self._orjson_module is None:
            raise ImportError(
                f"orjson not available. Install with: pip install 'gua[orjson]' or pip install orjson\n"
                f"Original error: {self._import_error}"
            )
    
    def dumps(self, obj: Any) -> str:
        self._check_available()
        # orjson返回bytes，需要解码为str
        orjson = cast(Any, self._orjson_module)
        return orjson.dumps(obj, option=orjson.OPT_SERIALIZE_NUMPY).decode()
    
    def loads(self, s: str) -> Any:
        self._check_available()
        orjson = cast(Any, self._orjson_module)
        return orjson.loads(s)
    
    @property
    def name(self) -> str:
        return "orjson"
    
    @property
    def available(self) -> bool:
        """检查orjson是否可用"""
        return self._orjson_module is not None


def _create_provider(provider_name: str) -> JSONProvider:
    """创建JSON提供者实例"""
    if provider_name == "standard":
        return StandardJSON()
    elif provider_name == "orjson":
        provider = OrjsonJSON()
        if not provider.available:
            raise ImportError(
                f"orjson not available. Install with: pip install 'gua[orjson]' or pip install orjson\n"
                f"Original error: {provider._import_error}"
            )
        return provider
    elif provider_name == "auto":
        # 自动选择最佳可用库
        provider = OrjsonJSON()
        if provider.available:
            return provider
        else:
            return StandardJSON()
    else:
        raise ValueError(f"Unknown JSON provider: {provider_name}")


class JSONManager:
    """JSON管理器 - 全局单例，管理JSON提供者"""
    
    def __init__(self, provider_name: str = "auto"):
        self._provider_name = provider_name
        self._provider: Optional[JSONProvider] = None
        self._provider_cache: Dict[str, JSONProvider] = {}
    
    def get_provider(self, provider_name: Optional[str] = None) -> JSONProvider:
        """获取JSON提供者实例"""
        name = provider_name or self._provider_name
        
        if name not in self._provider_cache:
            self._provider_cache[name] = _create_provider(name)
        
        return self._provider_cache[name]
    
    def set_provider(self, provider_name: str):
        """设置默认JSON提供者"""
        self._provider_name = provider_name
        self._provider = None  # 重置缓存
    
    @property
    def current_provider_name(self) -> str:
        """获取当前提供者名称"""
        return self._provider_name
    
    @property
    def current_provider(self) -> JSONProvider:
        """获取当前提供者实例"""
        if self._provider is None:
            self._provider = self.get_provider()
        return self._provider
    
    def dumps(self, obj: Any, provider_name: Optional[str] = None) -> str:
        """序列化对象为JSON字符串"""
        provider = self.get_provider(provider_name)
        return provider.dumps(obj)
    
    def loads(self, s: str, provider_name: Optional[str] = None) -> Any:
        """从JSON字符串反序列化"""
        provider = self.get_provider(provider_name)
        return provider.loads(s)
    
    def get_info(self) -> Dict[str, Any]:
        """获取当前JSON配置信息"""
        return {
            "provider": self.current_provider_name,
            "available_providers": list(self._provider_cache.keys()),
            "current_provider_class": self.current_provider.__class__.__name__
        }


# 全局JSON管理器实例
_json_manager = JSONManager()


def get_json_manager() -> JSONManager:
    """获取全局JSON管理器"""
    return _json_manager


def set_json_provider(provider_name: str):
    """设置全局JSON提供者"""
    _json_manager.set_provider(provider_name)


def json_dumps(obj: Any, provider_name: Optional[str] = None) -> str:
    """统一的JSON序列化函数 - 替代所有分散的json.dumps调用"""
    return _json_manager.dumps(obj, provider_name)


def json_loads(s: str, provider_name: Optional[str] = None) -> Any:
    """统一的JSON反序列化函数"""
    return _json_manager.loads(s, provider_name)


def get_json_info() -> Dict[str, Any]:
    """获取JSON配置信息"""
    return _json_manager.get_info()